<?php
/**
 * 拍单模块逻辑层
 */
namespace AuctionBack\Logic;

use AuctionBack\Model\OrderModel;
use AuctionCore\System\AuctionException;

class OrderLogic
{

    Protected $autoCheckFields = false;

    public $order_id = null;

    /**
     * 构造
     *
     * @param  int $order_id 拍单编号 或 拍单id
     *
     */
    public function __construct($order_no_or_id)
    {
        if (is_numeric($order_no_or_id)) {
            $this->order_id = $order_no_or_id;
        } else {
            $r = D('order', 'Model')->field('order_id')->where("order_no='{$order_no_or_id}'")->find();
            if ($r && count($r) > 0) {
                $this->order_id = $r['order_id'];
            } else {
                AuctionException::make_throw('700002');
            }
        }
    }

    /**
     * 拍单详情，以及拍单状态等。
     *
     * @return array
     */
    public function detail()
    {
        return D('order', 'Model')->where("order_id='{$this->order_id}'")->find();
    }


    /**
     * 更新拍单
     *
     * @param array $info 要更新的拍单信息
     * @param array $map 条件
     *
     * @return boolean
     */
    public function update($info, $map = array())
    {
        if (empty($map)) {
            $map['order_id'] = array('eq', $this->order_id);
        }
        $info['last_time'] = date('Y-m-d H:i:s');
        return D('order', 'Model')->where($map)->save($info);
    }

    /**
     * 按条件筛选拍单(多条)
     * @param array $data
     *
     * @return array
     */
    public static function getOrderInfos($data)
    {
        return D('order', 'Model')->field('order_id')->where($data)->select();
    }
    
    /**
     * 根据拍单ID找对应采购单信息
     * @return array
     */
    public function getPurchaseByOrderId()
    {
        $map = [];
        $map['o.order_id'] = $this->order_id;
        $purchaseInfo = M('order')->alias('o')->field('po.*')
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join(C('DB_PREFIX') . "purchase_order as po ON po.`sid` = c.`sid`")
            ->where($map)->find();
        return $purchaseInfo;
    }

    /**
     * 根据报告ID获取最新的拍单
     * @param $carId
     * @return mixed
     */
    public static function getLatestOrderByCarId($carId)
    {
        $map = [
            'car_id' => $carId
        ];

        return D('order', 'Model')->where($map)->order("order_id DESC")->find();
    }
}
